﻿using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Navigation;
using Caliburn.Micro;
using Caliburn.Micro.BindableAppBar;
using Microsoft.Phone.Controls;
using OsmerFvg.Helpers;
using OsmerFvg.ViewModels;

namespace OsmerFvg
{
    public class AppBootstrapper : PhoneBootstrapper
    {
        PhoneContainer _container;

        protected override void Configure()
        {
            if (Execute.InDesignMode)
                return;

            _container = new PhoneContainer();

            _container.RegisterPhoneServices(RootFrame);
            _container.PerRequest<MainPageViewModel>();
            _container.PerRequest<ForecastZoomViewModel>();
            _container.PerRequest<AboutPageViewModel>();
            _container.PerRequest<RadarPageViewModel>();
            _container.PerRequest<RadarZoomViewModel>();
            _container.PerRequest<WebCamsViewModel>();
            _container.PerRequest<WebCamsZoomViewModel>();

            AddCustomConventions();
        }

        static void AddCustomConventions()
        {

            // App Bar Conventions
            ConventionManager.AddElementConvention<BindableAppBarButton>(
                Control.IsEnabledProperty, "DataContext", "Click");
            ConventionManager.AddElementConvention<BindableAppBarMenuItem>(
                Control.IsEnabledProperty, "DataContext", "Click");
        }

        protected override PhoneApplicationFrame CreatePhoneApplicationFrame()
        {
            var frame = new PhoneApplicationFrame { UriMapper = new AssociationUriMapper() };
            return frame;
        }

        protected override object GetInstance(Type service, string key)
        {
            return _container.GetInstance(service, key);
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return _container.GetAllInstances(service);
        }

        protected override void BuildUp(object instance)
        {
            _container.BuildUp(instance);
        }

    }

    public class AssociationUriMapper : UriMapperBase
    {
        public override Uri MapUri(Uri uri)
        {
            if (uri.OriginalString.Contains("AboutPageView"))
                return uri;
            
            return !PhoneUtilities.HasInternetConection ? new Uri("/Views/NoConnectionPageView.xaml", UriKind.Relative) : uri;
        }
    }
}
